﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Agro.Library;
using Agro.Models;
using Agro.Services;
using Ninject;
using SN.Core;
using SN.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Agro.Web.Areas.SystemManage.Controllers
{
    public class UserController : BaseController
    {

        [Inject]
        public IUserService UserService { get; set; }


        [AuthorizeMenu]
        public ActionResult UserList()
        {
            ViewBag.CurrUserOrg = CurrUser.UserInfo.User_OrganizationID.ToString();
            ViewBag.IsAdmin = CurrUser.UserInfo.IsAdmin() ? "1" : "0";
            ViewBag.pid = CurrUser.UserInfo.User_OrganizationID;//组织结构树的pid
            return View();
        }

        [HttpPost]
        public ActionResult GetUserList(string organizeId, QueryBase query)
        {
            WhereClip where = WhereClip.All;
            if (!string.IsNullOrEmpty(organizeId))
                if (!CurrUser.UserInfo.IsAdmin() && organizeId.Trim().ToString() == CurrUser.UserInfo.User_OrganizationID.ToString())//如果不是管理员，则不显示当前部门的用户
                    where = where &&  T_Organization._.Organization_ParentID == organizeId;
                else
                    where = where && WhereClip.Bracket(T_User._.User_OrganizationID == organizeId || T_Organization._.Organization_ParentID == organizeId);
            else//如果organizeId为空，则什么都不返回。
                return Json("");
            var list = UserService.GetUserList(query, where);
            return JqGrid(list, query);
        }

        public ActionResult UserEdit(string organizationid, string id)
        {
            T_User user = new T_User();


            if (string.IsNullOrEmpty(id))
            {
                user.User_OrganizationID = (string.IsNullOrEmpty(organizationid) ? -1 : int.Parse(organizationid));
                ViewBag.type = "add";
            }
            else
            {
                user = UserService.GetEntity<T_User>(T_User._.User_ID == id);
                ViewBag.type = "edit";
            }
            ViewBag.User_OrganizationName = UserService.GetOrganizationName(organizationid);
            return View(user);
        }

        [HttpPost]
        public ActionResult Save_User(int User_ID, FormCollection collection)
        {
            T_User user = new T_User();
            if (User_ID > 0)
            {
                user = UserService.GetEntity<T_User>(T_User._.User_ID == User_ID);
            }
            else
            {
                user.User_CreateDate = DateTime.Now.ToString("yyyy-MM-dd");
                user.User_CreateUserID = CurrUser.UserInfo.User_Name;
            }
            UpdateModel(user, collection);
            string msg = string.Empty;
            //user.User_Password = SN.Core.Helper.Cryptography.MD5Encrypt(user.User_Password);//密码通过md5加密，暂不用
            UserService.SaveUser(user, CurrUser, out msg);
            return SNJson(user.User_ID, msg);
        }

        [HttpPost]
        public ActionResult Delete_User(string ids)
        {
            string msg = string.Empty;
            UserService.DeleteUsers(ids, out msg);
            return SNJson(msg);
        }

        public ActionResult ChangePassword()
        {
            string Msg = string.Empty;
            T_User User = UserService.GetEntity<T_User>(T_User._.User_ID == CurrUser.UserInfo.User_ID);
            //CurrUser
            return View(User);
        }
        [HttpPost]
        public ActionResult SetPassword(FormCollection collection)
        {
            string UserId = collection["User_ID"].ToString();
            string newPasswrod = collection["Password1"].ToString();
            //newPasswrod = SN.Core.Helper.Cryptography.MD5Encrypt(newPasswrod);
            string Msg = UserService.ChangePassword(UserId, newPasswrod);
            return SNJson(Msg);
        }

        public ActionResult UserAction(int id)
        {
            ViewBag.UserID = id;
            ViewBag.Menus = GetMenuOptionList();
            return View();
        }

        public ActionResult UserMenu(int id)
        {
            ViewBag.UserID = id;
            return View();
        }

        [HttpPost]
        public ActionResult SaveUserActions(int userId, int menuId, string actionIds)
        {
            UserService.SaveUserActions(userId, menuId, actionIds);
            return SNJson(string.Empty);
        }

        [HttpPost]
        public ActionResult SaveUserMenus(int userId, string menuIds)
        {
            string Msg = UserService.SaveUserMenus(userId, menuIds);
            return SNJson(Msg);
        }


        public ActionResult GetUserMenuTreeNodes(int id)
        {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("MenuID", typeof(int));
            dtResult.Columns.Add("FatherMenuID", typeof(int));
            dtResult.Columns.Add("Name", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Menu> menuList = UserService.GetEntityList<T_Menu>(WhereClip.All && new Field("isnull(menu_isdel,'0')") == "0");
            menuList = menuList.OrderBy(m => m.Menu_Order).ToList();
            IList<T_UserMenu> userMenuList = UserService.GetEntityList<T_UserMenu>(T_UserMenu._.UserID == id);
            DataRow dr = null;
            foreach (var item in menuList)
            {
                dr = dtResult.NewRow();
                dr["MenuID"] = item.Menu_ID;
                dr["FatherMenuID"] = item.Menu_ParentID;
                dr["Name"] = item.Menu_NAME;
                dr["checked"] = userMenuList.Count(m => m.MenuID == item.Menu_ID) > 0;
                dtResult.Rows.Add(dr);
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }


        public ActionResult GetUserActionTreeNodes(int userId, int menuId)
        {
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("ActionID", typeof(int));
            dtResult.Columns.Add("ActionName", typeof(string));
            dtResult.Columns.Add("checked", typeof(bool));
            IList<T_Action> actionList = UserService.GetEntityList<T_Action>(T_Action._.MenuID == menuId);

            IList<T_UserAction> userActionList = UserService.GetEntityList<T_UserAction>(T_UserAction._.UserID == userId);
            DataRow dr = null;
            foreach (var action in actionList)
            {
                dr = dtResult.NewRow();
                dr["ActionID"] = action.ActionID;
                dr["ActionName"] = string.Format("{0}({1})", action.ActionName, action.ActionCode);
                dr["checked"] = userActionList.Count(m => m.ActionID == action.ActionID) > 0;
                dtResult.Rows.Add(dr);
            }
            string result = JsonConvert.SerializeObject(dtResult, new DataTableConverter());
            return Content(result);
        }

        IList<SelectListItem> GetMenuOptionList()
        {
            IList<T_Menu> topMenu = UserService.GetEntityList<T_Menu>(T_Menu._.Menu_ParentID == 0 && new Field("isnull(menu_isdel,'0')") == "0").OrderBy(m => m.Menu_Order).ToList();

            List<SelectListItem> optionList = new List<SelectListItem>();
            foreach (var item in topMenu)
            {
                optionList.Add(new SelectListItem { Text = item.Menu_NAME, Value = item.Menu_ID.ToString() });
                recurMenuList(optionList, item.Menu_ID, "|----");
            }
            return optionList;
        }

        void recurMenuList(IList<SelectListItem> optionList, int fatherId, string prefix)
        {
            var list = UserService.GetEntityList<T_Menu>(T_Menu._.Menu_ParentID == fatherId && new Field("isnull(menu_isdel,'0')") == "0").OrderBy(m => m.Menu_Order).ToList();
            foreach (var item in list)
            {
                optionList.Add(new SelectListItem { Text = prefix + item.Menu_NAME, Value = item.Menu_ID.ToString() });
                recurMenuList(optionList, item.Menu_ID, prefix + "----");
            }
        }
    }
}
